package com.ctos.ojbackendjudgeservice.mq;

import com.ctos.ojbackendcommon.common.ErrorCode;
import com.ctos.ojbackendcommon.exception.BusinessException;
import com.ctos.ojbackendjudgeservice.judge.JudgeService;
import com.ctos.ojbackendmodel.entity.QuestionSubmit;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import static com.ctos.ojbackendcommon.constant.RabbitMqConstant.JUDGE_QUESTION_QUEUE_NAME;

@Component
@Slf4j
public class QuestionMessageConsumer {

    @Resource
    JudgeService judgeService;

    // 指定程序监听的消息队列和确认机制
    @SneakyThrows
    @RabbitListener(queues = {JUDGE_QUESTION_QUEUE_NAME}, ackMode = "MANUAL")
    public void receiveMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        if (StringUtils.isBlank(message)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "消息为空");
        }
        Long id = Long.parseLong(message);
        try {
            QuestionSubmit questionSubmit = judgeService.doJudge(id);
            if (questionSubmit == null){
                channel.basicNack(deliveryTag, false,false);
            }
        } catch (Exception e) {
            log.error("判题执行错误"+e);
            channel.basicNack(deliveryTag, false,false);
        }
        channel.basicAck(deliveryTag, false);
    }

}
